import { Component, ElementRef, EventEmitter, Input, OnChanges, OnInit, Output, Renderer2, SimpleChanges, ViewChild } from '@angular/core';
import { NzModalService } from 'ng-zorro-antd/modal';
import { FeeEnquiryService } from 'src/app/service/fee-enquiry/fee-enquiry.service';
import { PayService } from 'src/app/service/fee-enquiry/pay.service';
import { MessageService } from 'src/app/service/message.service';
const qrcode = require('arale-qrcode')

@Component({
  selector: 'app-pay',
  templateUrl: './pay.component.html',
  styleUrls: ['./pay.component.scss']
})
export class PayComponent implements OnInit, OnChanges {

  constructor(
    private pay: PayService,
    private feeEnquiry: FeeEnquiryService,
    private message: MessageService,
    public renderer2: Renderer2,
    private modal: NzModalService
  ) { }
  ngOnChanges(changes: SimpleChanges): void {
    if(changes['nzVisible']?.currentValue){
      if(parseFloat(this.data['total']) >= parseFloat(this.data['prepayAmt'])){
        this.actFee = parseFloat((parseFloat(this.data['total']) - parseFloat(this.data['prepayAmt'])).toFixed(2))
      }
    }
  }
  actFeeChange(){
    // if(this.actFee < this.data.total){
    //   this.message.info('实缴金额需大于等于应缴金额')
    // }
  }

  @Input() data: any = null
  @Input() nzVisible = false
  @Input() actFee = 0
  @Output() nzVisibleChange = new EventEmitter()
  @Output() onClose = new EventEmitter()
  payType: string = 'weChatPay' // ALiPay

  ngOnInit(): void {
  }

  nzOnCancel(){
    this.nzVisible = false
    this.nzVisibleChange.emit(false)
  }
  nzOnOk(){
    if(Number(this.actFee).toString() === 'NaN'){
      this.message.error('输入的金额不合法')
      return
    }

    // 缴纳金额 + 余额需要大于等于欠费总额
    if(parseFloat((Number(this.actFee) + Number(this.data['prepayAmt'])).toFixed(2)) < Number(this.data.total)){
      this.message.error('缴费金额加余额需大于等于欠费金额')
      return
    }

    // 预付费抵扣 欠费小于等于余额
    if(parseFloat(this.data['total']) <= parseFloat(this.data['prepayAmt'])){
      // 无欠费
      if(Number(this.data.total) <= 0){
        this.modal.confirm({
          nzContent: '当前无欠费，是否进行充值？',
          nzOnOk:() => {
            if(Number(this.actFee) <= 0){
              this.message.error('充值金额需大于0')
              return
            }
            this.launchPay()
          }
        })
      }else{
        if(Number(this.actFee) <= 0){
          this.modal.confirm({
            nzContent: '当前编号余额充足，是否直接抵扣？',
            nzOnOk: () => {
              console.log('直接进行抵扣')
            }
          })
          return
        }
        if(Number(this.actFee) > 0){
          this.modal.confirm({
            nzContent: '当前编号余额充足，可直接抵扣，多缴部分将继续存为此编号余额',
            nzOnOk: () => {
              this.launchPay()
            }
          })
          return
        }
      }
      return
    }
    
    this.launchPay()
  }

  nzOnPayCancel(){
    this.payModalVisible = false
    console.log('关闭支付')
    if(this.payCodeStatus === 'paySuccess'){
      this.onClose.emit()
    }else{
      this.onClose.emit(this.outTradeNo)
    }
  }

  payModalVisible = false
  payCodeStatus = ''
  payCodeText = ''
  launchPay(){
    this.nzVisible = false
    this.nzVisibleChange.emit(false)
    this.payModalVisible = true

    const payData = {} as any
    payData['productName'] = "东营智慧水务"
    payData['totalFee'] = (Number(this.actFee) * 100).toFixed(0)
    // payData['owedFee'] = (Number(this.data['total']) * 100).toFixed(0)
    payData['usageCode'] = this.data['code']
    payData['month'] = this.data['month']
    payData['frontCode'] = 'WT'
    // 支持预付费
    payData['prepayAmt'] = this.data['prepayAmt']
    payData['owedFee'] = this.data['total']

    this.isSpinning = true
    this.payCodeText = ''
    this.payCodeStatus = ''

    if(this.payType === 'weChatPay'){ // 微信支付
      this.launchWeChatPay(payData)
    }
    if(this.payType === 'ALiPay'){ // 支付宝支付
      this.launchAliPay(payData)
    }
  }
  launchWeChatPay(payData: any){
    this.pay._launchPay(payData).subscribe({
      next: (res: any) => {
        this.launchPaySuccess(res)
      },
      error: error => {
        this.launchPayError(error)
      }
    })
  }
  launchAliPay(payData: any){
    this.pay._launchAliPay(payData).subscribe({
      next: (res: any) => {
        console.log(res)
        this.launchPaySuccess(res)
      },
      error: error => {
        console.log(error)
        this.launchPayError(error)
      }
    })
  }
  payByBalance(){
    let param = {
      usageCode: this.data['usageCode'],
      month: this.data['month'],
      frontCode: 'WXMINI',
      prepayAmt: this.data['prepayAmt'],//账户余额
      owedFee: this.data['total'] //欠费金额
    }
    this.pay._payByBalance(param).subscribe({
      next: (res: any) => {
        if(res.result === 'success'){
          this.message.successModal('抵扣成功')
        }else{
          this.message.successModal('抵扣失败,请重试')
        }

      },
      error: (err: any) => {
        this.message.successModal('抵扣失败,请重试')
      }
    })
  }
  launchPaySuccess(res: any){
    if(res && res.message){
      this.getPayCode(res.codeUrl)
      this.payWaiting(res.outTradeNo)
      this.payCodeStatus = 'success'
      return
    }
    this.payCodeStatus = 'error'
    this.payCodeText = '获取付款码失败'
    this.isSpinning = false
  }
  launchPayError(err: any){
    console.log(err)
    this.payCodeStatus = 'error'
    this.payCodeText = '获取付款码失败'
    this.isSpinning = false
  }

  payTypeChange(e: string){
    this.payType = e
    if(this.codeImgObj){
      this.renderer2.removeChild(this.payCodeImg?.nativeElement, this.codeImgObj);
    }

    this.isSpinning = true
    this.payCodeText = ''
    this.payCodeStatus = ''

    if(!this.outTradeNo){
      this.launchPay()
      return
    }

    this.feeEnquiry.cancelOrder(this.outTradeNo).subscribe({
      next: (res: { result: string }) => {
        this.launchPay()
      },
      error: () => {
        this.launchPay()
        // this.message.info('切换支付方式失败，请刷新页面重试')
      }
    })
  }

  isSpinning = false
  codeImgObj: any;
  @ViewChild('payCodeImg') private payCodeImg: ElementRef | undefined;
  getPayCode(codeUrl: string){
    this.codeImgObj = new qrcode({
      text: codeUrl,
      render: 'svg',
      size: 190
    })
    console.log('ss ===>', this.codeImgObj);

    this.renderer2.appendChild(this.payCodeImg?.nativeElement, this.codeImgObj);
    this.isSpinning = false;
  }
  outTradeNo = ''
  payWaiting(outTradeNo: string){
    this.outTradeNo = outTradeNo;
    this.pay._payWaiting(outTradeNo, this.payType).subscribe({
      next: (res: any) => {
        if(this.outTradeNo === outTradeNo){
          if(res === 'success'){
            this.payCodeStatus = 'paySuccess';
            this.payCodeText = '支付成功'
          }else{
            this.waitFailed();
          }
        }
      },
      error: error => {
        this.waitFailed()
      }
    })
  }
  waitFailed(){
    this.payCodeStatus = 'error';
    this.payCodeText = '付款码失效';
    this.renderer2.removeChild(this.payCodeImg?.nativeElement, this.codeImgObj);
  }

  close(){
    this.payModalVisible = false
    this.onClose.emit()
  }
}

// private String usageCode;//用户编号
// private String productName;
// private String totalFee;
// private String frontCode;//支付来源，政务服务网（ZW）、微信公众号(WX)、穗好办（SHB）、网上营业厅(WT)、微信小程序(WXMINI)
// private String code;//登录操作码，微信小程序支付需要
